package com.sankuai.project.controller;


import com.alibaba.excel.EasyExcel;
import com.sankuai.project.annotation.LogAnnotation;
import com.sankuai.project.enums.ResultCodeEnum;
import com.sankuai.project.exception.TestException;
import com.sankuai.project.model.*;
import com.sankuai.project.model.convertData.ConvertUtils;
import com.sankuai.project.service.BatchRunRedisUtil;
import com.sankuai.project.utils.HttpClientUtils;
import com.sankuai.project.utils.JsonUtil;
import lombok.Data;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.LongAdder;

@RestController
@RequestMapping("user")
@Slf4j
public class userController {

    @Resource(name = "taskExecutor")
    private Executor taskExecutor;

    @Autowired
    private BatchRunRedisUtil batchRunRedisUtil;

    private LongAdder longAdder = new LongAdder();


    @LogAnnotation
    @PostMapping("/add")
    public String addUser(@RequestBody User user) {
        System.out.println("添加的user数据：" + user);
        return "addUser success";
    }

    @AllArgsConstructor
    @Data
    static class responseData {
        private Integer data;
        private String desc;
    }


    @PostMapping("/parrel")
    public R parrelReadData() {

        // 演示出现异常情况
        try {
            int a = 1 / 0;
        } catch (Exception e) {
            // 抛出自定义的异常
            throw new TestException(ResultCodeEnum.TEST_NUMBER);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("name", "李太白");
        return R.ok().data(data);


//        Map<Integer, Boolean> map = batchRunRedisUtil.integerBooleanMap();
//        return map;

//        long start = System.currentTimeMillis();
//        List<Integer> pageNum = new ArrayList<>();
//        for (int i = 0; i < 1000; i++) {
//            pageNum.add(i);
//        }
//
//        List<CompletableFuture<Map<Integer, Boolean>>> futures = pageNum.stream()
//                .map(x -> CompletableFuture.supplyAsync(() -> this.getDataFromRpcMethod(x), executor))
//                .collect(Collectors.toList());
//
//        CompletableFuture<Void> voidCompletableFuture =
//                CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
//        List<Map<Integer, Boolean>> result = futures.stream().map(this::tryAndGet).collect(Collectors.toList());


//        List<CompletableFuture<List<responseData>>> futures = new ArrayList<>();
//
//        List<List<Integer>> partition = Lists.partition(pageNum, 20);
//        CompletableFuture<List<responseData>> future = null;
//        for (List<Integer> page : partition) {
////            List<responseData> dataFromRpc = getDataFromRpc(page);
//
//            future = CompletableFuture.supplyAsync(() -> {
//                return getDataFromRpc(page);
//            }, executor);
//            futures.add(future);
//        }
//        CompletableFuture<Void> voidCompletableFuture =
//                CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
//
//        List<responseData> responseData = null;
//        List<responseData> collect =
//                futures.stream().map(x -> {
//                    try {
//                        return x.get();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    } catch (ExecutionException e) {
//                        e.printStackTrace();
//                    }
//                    return null;
//                }).flatMap(Collection::stream).collect(Collectors.toList());
//
//        System.out.println(collect);


//        long end = System.currentTimeMillis();
//        long timeTotal = end - start;
//        //log.info("程序总耗时为：{}", end - start);
//        longAdder.add(timeTotal);
//        log.info("程序总耗时为：{}", longAdder.doubleValue());
//        return result;
    }

    private Map<Integer, Boolean> tryAndGet(CompletableFuture<Map<Integer, Boolean>> mapCompletableFuture) {
        Map<Integer, Boolean> responseData = new HashMap<>();
        try {
            responseData = mapCompletableFuture.get(10, TimeUnit.MILLISECONDS);
        } catch (InterruptedException | TimeoutException | ExecutionException e) {
            throw new RuntimeException();
        }
        return responseData;
    }

//    private responseData tryAndGet(CompletableFuture<responseData> responseDataCompletableFuture) {
//        responseData responseData = null;
//        try {
//            responseData = responseDataCompletableFuture.get();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }
//        return responseData;
//    }

    private Map<Integer, Boolean> getDataFromRpcMethod(Integer x) {
        Map<Integer, Boolean> map = new HashMap<>();
        map.put(x, x % 2 == 0 ? true : false);
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return map;
    }

    private List<responseData> getDataFromRpc(List<Integer> page) {
        List<responseData> input = new ArrayList<>();
        try {
            for (int i : page) {
                input.add(new responseData(i, i + "响应数据"));
                Thread.sleep(10);
            }
        } catch (Exception e) {
            log.error("未知异常", e);
        }
        return input;
    }


    @PostMapping("/test")
    public String testDate() {


        String fileName = "D:\\ceshi.xlsx";
        List<TotalData> input = new ArrayList<>();
        String url = "https://gd.tzxm.gov.cn/tzxmspweb/api/publicityInformation/selectByPageBA";
        String UrlDetail = "https://gd.tzxm.gov.cn/tzxmspweb/api/publicityInformation/selectBaProjectInfo";

        for (int i = 3000; i < 3873; i++) {
            Map<String, String> headers = new HashMap<>();
            headers.put("X-Requested-With", "XMLHttpRequest");
            RequestData requestData = new RequestData();
            requestData.setFlag("1");
            requestData.setNameOrCode("光伏");
            requestData.setPageSize(15);
            requestData.setCity("");
            requestData.setPageNumber(i);

            String jsonParam = JsonUtil.objectToJson(requestData);
            try {
                String json = HttpClientUtils.doPostJson(url, jsonParam, headers);
                Root root = JsonUtil.jsonToPojo(json, Root.class);
                List<ListItemDetail> list = root.getData().getList();
                for (ListItemDetail itemDetail : list) {
                    DetailRequestData detailRequestData = new DetailRequestData(itemDetail.getBaId());
                    String jsonDetail = HttpClientUtils.doPostJson(UrlDetail, JsonUtil.objectToJson(detailRequestData),
                            headers);
                    DetailRoot detailRoot = JsonUtil.jsonToPojo(jsonDetail, DetailRoot.class);
                    TotalData totalDataTemp = ConvertUtils.convertData(itemDetail, detailRoot.getData());
                    input.add(totalDataTemp);
                }

            } catch (Exception e) {
                log.error("error", e);
            }
            log.info("一轮数据读取完毕" + i);
        }
        try {
            EasyExcel.write(fileName, TotalData.class).sheet("sheet1").doWrite(input);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("保存成功");
        return "OK";
//        String url = "https://gd.tzxm.gov.cn/tzxmspweb/api/publicityInformation/selectByPageBA";
//        String UrlDetail = "https://gd.tzxm.gov.cn/tzxmspweb/api/publicityInformation/selectBaProjectInfo";
//        Map<String, String> headers = new HashMap<>();
//        headers.put("X-Requested-With", "XMLHttpRequest");
//        RequestData requestData = new RequestData();
//        requestData.setFlag("1");
//        requestData.setNameOrCode("光伏");
//        requestData.setPageSize(15);
//        requestData.setCity("");
//        requestData.setPageNumber(1);
//
//
//        String fileName = "D:\\ceshi.xlsx";
//
//        String jsonParam = JsonUtil.objectToJson(requestData);
//        try {
//            String json = HttpClientUtils.doPostJson(url, jsonParam, headers);
//            Root root = JsonUtil.jsonToPojo(json, Root.class);
//            List<ListItemDetail> list = root.getData().getList();
//            List<TotalData> input = new ArrayList<>();
//            for (ListItemDetail itemDetail : list) {
//                DetailRequestData detailRequestData = new DetailRequestData(itemDetail.getBaId());
//                String jsonDetail = HttpClientUtils.doPostJson(UrlDetail, JsonUtil.objectToJson(detailRequestData),
//                        headers);
//                DetailRoot detailRoot = JsonUtil.jsonToPojo(jsonDetail, DetailRoot.class);
//                System.out.println("detailRoot = " + detailRoot);
//
//                TotalData totalDataTemp = ConvertUtils.convertData(itemDetail, detailRoot.getData());
//                input.add(totalDataTemp);
//            }
//
//            EasyExcel.write(fileName, TotalData.class).sheet("sheet1").doWrite(input);
//        } catch (Exception e) {
//            log.error("error", e);
//        }
//        return "OK";
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Getter
    @Setter
    static class RequestData {
        private String flag;
        private String nameOrCode;
        private int pageSize;
        private String city;
        private int pageNumber;
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Getter
    @Setter
    static class DetailRequestData {
        private String baId;
    }
}


